<template>
  <div id="marquee-set">
    <common
    :loading='loading'
    :tableHeight='tableHeight'
    :searchShopName='searchShopName'
    :tableData='tableData'
    :pageObj='pageObj'
    @changeStore='changeStore'
    @changePageSize='changePageSize'
    @changePageIndex='changePageIndex'
    @viewHistory='viewHistory(arguments)'
    @allSet='allSet'
    @skipSlit='skipSlit(arguments)'></common>
    <!-- 批量设置组件 -->
    <select-shop :checkdList="checkdList" :titleObj='titleObj'
      :dataTree="dataTree"
      :modalShow="modalShow"
      @oncancel="selctshopCancel"
      @selctshop="volumeSet"
      v-if="modalShow"></select-shop>
    <!-- 二次modal弹框 -->
    <Modal
        v-model="setModalStatus"
        :transfer='false'
         :closable='true'
         :mask-closable='false'
         @on-cancel="cancelModal"
        title="设置配置项">
        <Row style="margin-left:20px">
          <Col>
            <Form ref="firmwareFormValidate" :model="firmwareFormValidate" :rules="firmwareRuleValidate" :label-width="110">
            <FormItem label="跑马灯颜色：" prop="marqueeColor">
              <Select v-model="firmwareFormValidate.marqueeColor" style="width:260px">
                <Option v-for="item in marqueeColorList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            <FormItem label="时间间隔(ms)：" prop="timeInterval" v-if="firmwareFormValidate.marqueeColor === '4'">
              <Select v-model="firmwareFormValidate.timeInterval" style="width:260px">
                <Option v-for="item in timeIntervalList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            </Form>
          </Col>
        </Row>
        <div slot="footer">
          <Button style="margin-right:10px;width:80px" @click="skipPrevious">上一步</Button>
          <Button type="primary" style='width:80px' @click="sureSet">确定</Button>
        </div>
    </Modal>
    <!-- 侧边栏 -->
    <Drawer :title="drawTitle" :closable="true" width='640' :transfer='false' v-model="openDraw" class="history-draw">
      <Row type='flex' justify="center" style="padding-top:50px;border-top: 1px solid #e8eaec;" v-if="drawTitle === '跑马灯设置'">
        <Col>
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="110">
            <FormItem label="门店名称：" prop="shopName">
              <Input placeholder="门店名称" v-model='formValidate.shopName' style="width:260px" :disabled='true' />
            </FormItem>
            <FormItem label="跑马灯开关：" prop="marqueeSwitch">
              <i-switch :value="formValidate.marqueeSwitch === '0'? false: (formValidate.marqueeSwitch === '1'? true:false)" @on-change="changeMarqueeSwitch">
                <span slot="open">开</span>
                <span slot="close">关</span>
              </i-switch>
            </FormItem>
            <FormItem label="跑马灯颜色：" prop="marqueeColor">
              <Select v-model="formValidate.marqueeColor" style="width:260px">
                <Option v-for="item in marqueeColorList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            <FormItem label="时间间隔(ms)：" prop="timeInterval" v-if="formValidate.marqueeColor === '4'">
              <Select v-model="formValidate.timeInterval" style="width:260px">
                <Option v-for="item in timeIntervalList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
          </Form>
        </Col>
      </Row>
      <div v-if="drawTitle === '历史记录'">
        <Table stripe :columns="columnsHistory" :data="tableHistoryData" :height='historyTableHeight'>
          <template slot-scope="{ row }" slot="marqueeSwitch">
            <div v-if='row.configValue'>
              <span>{{row.configValue.split('|')[0] === '0' ? '关': row.configValue.split('|')[0] === '1' ? '开' : ''}}</span>
            </div>
            </template>
          <template slot-scope="{ row }" slot="marqueeColor">
            <div v-if='row.configValue'>
              <span>{{['红色','绿色','蓝色','七彩色'][row.configValue.split('|')[1] - 1 ]}}</span>
            </div>
          </template>
          <template slot-scope="{ row }" slot="timeInterval">
            <div v-if='row.configValue'>
              <span>{{row.configValue.split('|')[2]}}</span>
            </div>
          </template>
        </Table>
      </div>
      <div class="demo-drawer-footer">
          <div v-if="drawTitle === '跑马灯设置'">
            <Button style="margin-right: 20px" class="draw-btn" @click="openDraw = false">取消</Button>
            <Button type="primary" class="draw-btn" @click="singleSet" :disabled='isDisabled'>确定</Button>
          </div>
          <Row type='flex' justify="end" v-if="drawTitle === '历史记录'">
            <Col>
            <Page :total="historyObj.total"
                :current="historyObj.pageIndex"
                :page-size="historyObj.pageSize"
                show-sizer
                show-total
                @on-change='changeHistoryPageIndex'
                @on-page-size-change='changeHistoryPageSize' />
            </Col>
          </Row>
        </div>
    </Drawer>
  </div>
</template>

<script>
import { iterationMarqueeList, iterationHistoryList, setDicSave, getDicQuery } from '@/api/setting'
import SelectShop from '@/view/components/select-machine/select-machine.vue'
import common from '@/view/setting/components/common.vue'
import volumeStore from '@/view/setting/components/own-use/volumeStore'
import mixins from '@/view/setting/components/own-use/mixins'
export default {
  name: 'global_setting_page_21',
  mixins: [mixins, volumeStore],
  components: {
    SelectShop,
    common
  },
  watch: {
    'formValidate.marqueeColor' (val) {
      if (val === '4') {
        if (this.formValidate.timeInterval === '0') {
          this.formValidate.timeInterval = ''
        }
      }
    }
  },
  computed: {
    tableHeight () {
      let height = this.tableData.length > 10 ? 520 : 0
      return height
    },
    historyTableHeight () {
      let height = 0
      if (this.tableHistoryData.length > 10) {
        height = (document.documentElement.clientHeight || document.body.clientHeight) - 103
      } else {
        height = 0
      }
      return height
    }
  },
  data () {
    return {
      isDisabled: false,
      loading: true,
      serachShopId: '',
      orgId: '',
      drawTitle: '跑马灯设置',
      openDraw: false,
      searchShopName: '',
      marqueeColorList: [
        // { value: '', label: '请选择' },
        { value: '1', label: '红色' },
        { value: '2', label: '绿色' },
        { value: '3', label: '蓝色' },
        { value: '4', label: '七彩色' }
      ],
      timeIntervalList: [
        // { value: '', label: '请选择' },
        { value: '10', label: '10' },
        { value: '50', label: '50' },
        { value: '100', label: '100' },
        { value: '200', label: '200' }
      ],
      firmwareFormValidate: {
        marqueeColor: '',
        timeInterval: ''
      },
      firmwareRuleValidate: {
        marqueeColor: { required: true, message: '跑马灯颜色不能为空', trigger: 'change' },
        timeInterval: { required: true, message: '时间间隔不能为空', trigger: 'change' }
      },
      formValidate: {
        shopName: '',
        marqueeSwitch: '',
        marqueeColor: '',
        timeInterval: ''
      },
      ruleValidate: {
        marqueeColor: { required: true, message: '跑马灯颜色不能为空', trigger: 'change' },
        timeInterval: { required: true, message: '时间间隔不能为空', trigger: 'change' }
      },
      tableData: [],
      tableHistoryData: [],
      columnsHistory: [
        {
          title: '发布时间',
          key: 'createTime',
          width: 150
        },
        {
          title: '跑马灯开关',
          slot: 'marqueeSwitch'
        },
        {
          title: '跑马灯颜色',
          slot: 'marqueeColor'
        },
        {
          title: '时间间隔(ms)',
          slot: 'timeInterval',
          width: 120
        },
        {
          title: '操作人',
          key: 'creatorName',
          width: 160
        }
      ]
    }
  },
  methods: {
    volumeSet (val) {
      this.modalShow = false
      this.setModalStatus = true
      this.checkdList = val
      // 此处请求选择好门店后，设置固件
    },
    changeMarqueeSwitch (value) {
      this.formValidate.marqueeSwitch = value ? '1' : '0'
    },
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    changeHistoryPageIndex (index) {
      this.historyObj.pageIndex = index
      this.getHistoryList()
    },
    changeHistoryPageSize (size) {
      this.historyObj.pageSize = size
      this.historyObj.pageIndex = 1
      this.getHistoryList()
    },
    skipSlit (argument) {
      this.$router.push({ name: 'marquee_slit', query: { shopName: argument[0].orgName, shopId: argument[0].orgId, type: argument[1] } })
    },
    changeStore (name) {
      this.searchShopName = name
      // this.serachShopId = name.value
      this.pageObj.pageIndex = 1
      this.getData()
    },
    viewHistory (argument) {
      this.openDraw = true
      this.orgId = argument[1].orgId
      if (argument[0] === '1') {
        this.drawTitle = '跑马灯设置'
        this.formValidate.shopName = argument[1].orgName
        this.searchSingleSet()
        // if (argument[1].configValue) {
        //   this.formValidate.marqueeSwitch = argument[1].configValue.split('|')[0]
        //   this.formValidate.marqueeColor = argument[1].configValue.split('|')[1]
        //   this.formValidate.timeInterval = argument[1].configValue.split('|')[2]
        // }
      } else {
        this.drawTitle = '历史记录'
        this.getHistoryList()
      }
    },
    // 查询单个设置
    searchSingleSet () {
      getDicQuery({
        shopId: this.orgId,
        'dictKeys': 'ledConfig',
        'merchantId': this.$store.state.user.merchantId,
        'msType': '1'
      }).then(res => {
        if (res.data.status === 200) {
          let ele = res.data.data[0].ledConfig
          if ((ele !== '0' || ele !== 0) && ele) {
            this.formValidate.marqueeSwitch = ele.split('|')[0]
            this.formValidate.marqueeColor = ele.split('|')[1]
            this.formValidate.timeInterval = ele.split('|')[2]
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    singleSet () {
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          this.isDisabled = true
          if (this.formValidate.marqueeColor !== '4') {
            this.formValidate.timeInterval = '0'
          }
          setTimeout(() => {
            setDicSave({
              msType: '1',
              merchantId: this.$store.state.user.merchantId,
              ledConfig: this.formValidate.marqueeSwitch + '|' + this.formValidate.marqueeColor + '|' + this.formValidate.timeInterval,
              shopIds: [this.orgId]
            }).then(res => {
              this.isDisabled = false
              if (res.data.status === 200) {
                this.$Message.success('设置成功！')
                this.openDraw = false
                this.getData()
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            })
          }, 200)
        }
      })
    },
    sureSet () {
      this.$refs.firmwareFormValidate.validate((valid) => {
        if (valid) {
          if (this.firmwareFormValidate.marqueeColor !== '4') {
            this.firmwareFormValidate.timeInterval = '0'
          }
          let arr = this.checkdList.map(item => {
            return item.id
          })
          setDicSave({
            msType: '1',
            merchantId: this.$store.state.user.merchantId,
            ledConfig: '1|' + this.firmwareFormValidate.marqueeColor + '|' + this.firmwareFormValidate.timeInterval,
            shopIds: arr
          }).then(res => {
            if (res.data.status === 200) {
              this.$Message.success('设置成功！')
              this.setModalStatus = false
              this.getData()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    },
    // 获取历史记录
    getHistoryList () {
      iterationHistoryList({
        merchantId: this.$store.state.user.merchantId,
        belongId: this.orgId,
        configKey: 'ledConfig',
        offset: this.historyObj.pageSize * (this.historyObj.pageIndex - 1),
        limit: this.historyObj.pageSize
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.tableHistoryData = result.data || []
          this.historyObj.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    },
    // 获取跑马灯列表
    getData () {
      this.loading = true
      iterationMarqueeList({
        merchantId: this.$store.state.user.merchantId,
        shopName: this.searchShopName,
        // shopId: this.serachShopId,
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.tableData = result.data || []
          this.pageObj.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    }
  },
  mounted () {
    this.getData()
  }
}
</script>

<style lang='less'>
#marquee-set{
  .draw-btn{
    width: 80px;
  }
  .ivu-drawer-body {
    padding: 0;
    height: calc(~"100% - 103px");
  }
  .ivu-drawer-header {
    border-bottom: 0;
  }
  .demo-drawer-footer{
    width: 640px;
    position: fixed;
    bottom: 0;
    right: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
}
</style>
